package com.hsy.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/userListServlet", initParams = {
        @WebInitParam(name = "encoding", value = "UTF-8")
})
public class LoginFilter implements Filter {
    // 过滤中文乱码的编码方式
    private String encoding = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 从 web.xml 中获取编码配置，如果没有则使用默认的 UTF-8
        String encodingParam = filterConfig.getInitParameter("encoding");
        if (encodingParam!= null) {
            encoding = encodingParam;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String requestURI = httpServletRequest.getRequestURI();
        // 设置请求编码
        if(requestURI.endsWith(".html")) {
            // 为了防止过滤html界面时出现乱码
            response.setContentType("text/html");
            response.setCharacterEncoding(null);
        }
        else {
            httpServletRequest.setCharacterEncoding(encoding);
            httpServletResponse.setCharacterEncoding(encoding);
            httpServletResponse.setContentType("text/html;charset=" + encoding);
        }
        // 获取会话
        HttpSession session = httpServletRequest.getSession(false);
        String loginURI = httpServletRequest.getContextPath() + "/index.html";


        // 不需要登录验证的页面或请求，直接放行
        if (requestURI.endsWith("/index.html") || requestURI.equals("http://localhost:8180")) {
            chain.doFilter(request, response);
        } else {
            boolean loggedIn = (session!= null && session.getAttribute("user")!= null);
            if (!loggedIn) {
                // 用户未登录，输出一段 JavaScript 代码弹出提示框，并且可以设置点击确定之后自动跳转到首页的时间
                httpServletResponse.getWriter().println("<script>alert('请先登录！'); setTimeout(function() { window.location.href='" + loginURI + "'; }, 1);</script>");
            } else {
                // 用户已登录，继续处理请求
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {
        // 释放资源，这里暂时不需要做什么
    }
}